package org.nmgyjt.springboot.utils;

import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.JOSEException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.entity.admin.IDAASUserResponse;
import org.nmgyjt.springboot.entity.admin.UserInfo;
import org.nmgyjt.springboot.entity.exception.BizException;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

@Slf4j
public class IDAASUserUtils {


    public static UserInfo selectUserInfoByOpenId(String openid) throws ParseException, JOSEException {
        String token = NMGYJTIDAASTokenUtils.getToken();
        if (StringUtils.isEmpty(token)) {
            log.info("get token exception >> 接口访问权限异常,请联系管理员");
            throw new BizException("接口访问权限异常,请联系管理员");
        }

        //log.info("getToken  >> success");
        HashMap<String, String> headerParams = new HashMap<>();
        Map<String, String> bodyParams = new HashMap<>();

        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + token);

        // log.info("token is >> {}", token);
        bodyParams.put("keywords", openid);
        bodyParams.put("object_type", "USER");

        String str = HttpUtils.httpGet("http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/search", bodyParams, headerParams);
        if (StringUtils.isNotEmpty(str)) {
            IDAASUserResponse userResponse = JSONObject.parseObject(str, IDAASUserResponse.class);
            List<UserInfo> data = userResponse.getData();
            if (!CollectionUtils.isEmpty(data)) {
                return data.get(0);
            }
        }
        return null;
    }


   // @Cacheable(cacheNames = "selectUserInfoFromIDAASByOpenIdV2", key = "#openid")
    public static UserInfo selectUserInfoFromIDAASByOpenIdV2(String openid) throws ParseException, JOSEException {

        Callable<UserInfo> userInfoTask = new UserInfoTask(openid);
        FutureTask<UserInfo> ft = new FutureTask<UserInfo>(userInfoTask);
        Thread thread = new Thread(ft);
        thread.start();
        UserInfo userInfo = null;
        try {                              //调用get方法会阻塞主线程等待结果，不调用则不会阻塞
            userInfo = ft.get();            //取得新创建的新线程中的call()方法返回的结果
            return userInfo;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return userInfo;
    }

}